package com.lxm.Exception;

import com.lxm.action.ActionBase;
import com.lxm.entity.ReturnMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * @author ：Administrator
 * @date :创建时间 2021/12/23 20:28
 * 全局异常拦截
 */
@ControllerAdvice
public class CommonExceptionAdvice  extends ActionBase {
    private final Logger logger = LoggerFactory.getLogger(getClass());


    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public ReturnMessage errorHandler(HttpServletRequest request, Exception ex){
        logger.info("拦截数据异常:{}", ex);
        String message = getMessage(ex);
        return error("未知异常,请联系管理员");
    }



    public String getMessage(Exception e){
        String message = null;
        try(StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) {
            pw.flush();
            sw.flush();
            message = sw.toString();
        }catch (IOException io) {
            io.printStackTrace();
        }
        return message;
    }

}
